package com.example.piece.net

import com.example.base.tools.ConfigTool
import com.example.base.tools.log.LoggingInterceptor
import com.example.piece.BuildConfig
import com.example.piece.constant.Key
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**  网络连接管理类  **/
@Suppress("MemberVisibilityCanBePrivate")
object NetManager {

    /**  后台返回数据正常  **/
    const val DATA_OK = 1
    /**  出现错误, 后台统一错误识别码  **/
    const val DATA_ERROR = 0
    /**  token 失效的识别码  **/
    const val TOKEN_INVALID = 401
    /**  系统正在维护，请稍后再试试  **/
    const val IN_MAINTENANCE = 500

    // 测试用内网地址(深远提供的云服务器)
   // const val BASE_SERVER_URL_TEST = "https://cretinzp.com:443/jokes-api/"
   const val BASE_SERVER_URL_TEST = "http://tools.cretinzp.com/jokes/"

    // 正式服务器公网地址(正式服务器地址)
    const val BASE_SERVER_URL_RELEASE = "http://tools.cretinzp.com/jokes/"
    //const val BASE_SERVER_URL_RELEASE = "https://cretinzp.com:443/jokes-api/"

    /**  用于请求接口的 API 对象  **/
    val apiService: ApiService by lazy {
        Retrofit.Builder()
            .baseUrl(getServerLocation())
            .addConverterFactory(GsonConverterFactory.create())
            .client(createClient())
            .build()
            .create(ApiService::class.java)
    }

    /**  获取服务器地址  **/
    public fun getServerLocation(): String {
        return if (BuildConfig.DEBUG) {
            val customServerLocation = ConfigTool.getString(Key.DataKey.SERVER_LOCATION)
            if (customServerLocation.isEmpty()) BASE_SERVER_URL_TEST
            else customServerLocation
        } else BASE_SERVER_URL_RELEASE
    }

    /**  创建 OkHttpClient  **/
    private fun createClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .connectTimeout(50000L, TimeUnit.MILLISECONDS)
            .readTimeout(10_000, TimeUnit.MILLISECONDS)
            .writeTimeout(30_000, TimeUnit.MILLISECONDS)
            .addInterceptor(AddHeadInterceptor)
            .addInterceptor(loggingInterceptor)

            .build()
    }

    /**  日志拦截器  **/
    private val loggingInterceptor: LoggingInterceptor by lazy {
        LoggingInterceptor.Builder()
            // 发布到生产环境需要改成false
            .loggable(BuildConfig.DEBUG)
            .request()
            .requestTag("Request")
            .response()
            .responseTag("Response")
            //.hideVerticalLine()// 隐藏竖线边框
            .build()
    }

    /**  Token 拦截器  **/
    private val AddHeadInterceptor: AddHeadInterceptor=AddHeadInterceptor()

}